Popular Searches
Popular Course Categories
Popular Courses

Applying Nested Loops

Applying Nested Loops

Loops and Iteration in Python

Applying Nested Loops in Python

Course: Python Training

Topic: Applying Nested Loops

Course Link: Python Training Course

Demo Registration: Register for a Course Demo

Academy Website: JustAcademy


1. Introduction to Nested Loops

A nested loop is a loop placed inside another loop. The loop containing the inner loop is called the outer loop, while the loop inside it is called the inner loop.

Nested loops are useful when a task requires processing combinations of values, working with rows and columns, generating patterns, comparing elements, or handling multidimensional data. They allow one repetition process to run inside another repetition process.

For example, suppose you want to print three rows, with four stars in every row. The outer loop controls the rows, and the inner loop controls the stars printed in each row.

for row in range(3):
    for column in range(4):
        print("*", end=" ")
    print()

Output:

* * * *
* * * *
* * * *

The outer loop executes three times. For every outer-loop iteration, the inner loop executes four times. This produces a total of 12 star-printing operations.

2. Learning Objectives

  • Understand the purpose and structure of nested loops.
  • Distinguish between outer and inner loops.
  • Trace the execution order of nested loops.
  • Use nested for loops and nested while loops.
  • Generate number, star, and character patterns.
  • Work with two-dimensional lists and matrices.
  • Understand nested-loop iteration counts and time complexity.
  • Apply break and continue within nested loops.
  • Identify common errors and improve loop efficiency.

3. Syntax of Nested Loops

A nested loop is created by placing one loop inside the indented body of another loop.

General Syntax

for outer_variable in outer_iterable:
    for inner_variable in inner_iterable:
        # Statements inside the inner loop
        statement

    # Statements inside the outer loop
    statement

The indentation determines which statements belong to each loop. The inner loop must be indented inside the outer loop.

Example

for i in range(2):
    for j in range(3):
        print(i, j)

Output:

0 0
0 1
0 2
1 0
1 1
1 2

First, the outer variable i is assigned 0. The inner variable j then takes the values 0, 1, and 2. After the inner loop finishes, i becomes 1, and the inner loop runs again from the beginning.

4. Understanding Outer and Inner Loops

Feature Outer Loop Inner Loop
Position Contains the inner loop. Located inside the outer loop.
Primary role Controls the main repetition. Performs repeated work for each outer iteration.
Execution Moves to the next iteration after its body finishes. Normally completes all its iterations before the outer loop advances.
Example use Controls the rows of a pattern. Controls the columns or symbols in each row.

5. How Nested Loops Execute

Consider the following code:

for i in range(1, 4):
    for j in range(1, 3):
        print("i =", i, "j =", j)

Output:

i = 1 j = 1
i = 1 j = 2
i = 2 j = 1
i = 2 j = 2
i = 3 j = 1
i = 3 j = 2

The execution proceeds in this order:

  1. The outer loop sets i = 1.
  2. The inner loop runs with j = 1 and then j = 2.
  3. The inner loop finishes, so the outer loop advances to i = 2.
  4. The inner loop runs again with j = 1 and j = 2.
  5. The same process occurs for i = 3.
  6. Both loops finish when their respective ranges are exhausted.

Because the outer loop runs three times and the inner loop runs twice per outer iteration, the print statement executes six times.

6. Applying Nested for Loops

Nested for loops are commonly used when both repetition levels work with a known sequence or iterable.

Example 1: Displaying Combinations

colors = ["Red", "Blue"]
sizes = ["Small", "Medium", "Large"]

for color in colors:
    for size in sizes:
        print(color, size)

Output:

Red Small
Red Medium
Red Large
Blue Small
Blue Medium
Blue Large

The code generates every combination of a color and a size. There are two colors and three sizes, resulting in six combinations.

Example 2: Multiplication Tables

for table in range(1, 4):
    for number in range(1, 6):
        print(table, "x", number, "=", table * number)
    print()

This program prints multiplication tables for 1, 2, and 3, with multipliers from 1 to 5. The outer loop selects the table, and the inner loop calculates each multiplication result.

Example 3: Printing Coordinates

for x in range(2):
    for y in range(3):
        print("Coordinate:", (x, y))

The program generates six coordinate pairs. This approach is useful for grids, board games, image pixels, and two-dimensional simulations.

7. Applying Nested while Loops

Nested while loops are useful when repetition at each level depends on a condition. Each loop needs a suitable condition and an update that allows it to terminate.

Example: Rows and Columns

row = 1

while row <= 3:
    column = 1

    while column <= 2:
        print("Row:", row, "Column:", column)
        column += 1

    row += 1

Output:

Row: 1 Column: 1
Row: 1 Column: 2
Row: 2 Column: 1
Row: 2 Column: 2
Row: 3 Column: 1
Row: 3 Column: 2

The variable column is reset to 1 at the beginning of each outer-loop iteration. Without resetting it, the inner loop would finish during the first row and might not run for later rows.

Best Practices for Nested while Loops

  • Initialize each loop-control variable before the loop that uses it.
  • Reset inner-loop variables when a new outer iteration requires them to start over.
  • Update every variable required for termination.
  • Check boundary conditions carefully to avoid infinite loops.

8. Creating Patterns with Nested Loops

Pattern printing is a common beginner exercise for learning nested loops. Usually, the outer loop controls the number of rows, while the inner loop controls the content of each row.

8.1 Square Star Pattern

for row in range(4):
    for column in range(4):
        print("*", end=" ")
    print()

Output:

* * * *
* * * *
* * * *
* * * *

The outer loop runs four times, and each row contains four stars.

8.2 Right-Angled Triangle

for row in range(1, 5):
    for column in range(row):
        print("*", end=" ")
    print()

Output:

*
* *
* * *
* * * *

The inner loop uses the current row number to decide how many stars to print. As the row number increases, the number of stars increases.

8.3 Increasing Number Pattern

for row in range(1, 5):
    for number in range(1, row + 1):
        print(number, end=" ")
    print()

Output:

1
1 2
1 2 3
1 2 3 4

The inner loop prints numbers from 1 up to the current row number.

8.4 Repeated Row Numbers

for row in range(1, 5):
    for column in range(row):
        print(row, end=" ")
    print()

Output:

1
2 2
3 3 3
4 4 4 4

Unlike the previous example, this program prints the outer-loop value repeatedly in each row.

8.5 Reverse Triangle

for row in range(4, 0, -1):
    for column in range(row):
        print("*", end=" ")
    print()

Output:

* * * *
* * *
* *
*

The outer loop counts down from 4 to 1. Each iteration prints fewer stars than the previous row.

9. Iterating Through Two-Dimensional Lists

A two-dimensional list is a list containing other lists. It can represent a table, a matrix, rows of records, or a grid of values. Nested loops are a natural way to process its rows and individual elements.

Example: Displaying a Matrix

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for value in row:
        print(value, end=" ")
    print()

Output:

1 2 3
4 5 6
7 8 9

The outer loop retrieves each row. The inner loop processes every value in that row. The final print() moves the output to a new line after each row.

Example: Calculating Row Totals

sales = [
    [100, 150, 200],
    [120, 180, 220],
    [90, 110, 160]
]

for row_number, row in enumerate(sales, start=1):
    total = 0

    for amount in row:
        total += amount

    print("Row", row_number, "total:", total)

Output:

Row 1 total: 450
Row 2 total: 520
Row 3 total: 360

The accumulator is reset for each row so that each total is calculated independently.

10. Using break and continue in Nested Loops

The break and continue statements affect the loop in which they are executed. In nested loops, understanding which loop is affected is especially important.

10.1 Using break

for i in range(1, 4):
    for j in range(1, 4):
        if j == 3:
            break
        print(i, j)

Output:

1 1
1 2
2 1
2 2
3 1
3 2

When j becomes 3, the inner loop terminates. The outer loop continues with its next value, so the same process repeats for each outer iteration.

10.2 Using continue

for i in range(1, 3):
    for j in range(1, 4):
        if j == 2:
            continue
        print(i, j)

Output:

1 1
1 3
2 1
2 3

When j equals 2, only that inner-loop iteration is skipped. The inner loop continues with the next value.

10.3 Exiting Both Loops

A normal break exits only the nearest enclosing loop. If a program needs to stop both loops, one simple approach is to use a flag.

found = False

for row in range(3):
    for column in range(4):
        if row == 1 and column == 2:
            found = True
            break
        print(row, column)

    if found:
        break

print("Search completed")

In this example, the inner loop stops when the target coordinate is reached. The outer loop then checks the flag and stops as well.

11. Nested Loops for Searching and Comparing Values

Nested loops can compare each item in one collection with items in another collection. They can also compare pairs of items from the same collection.

Example: Finding Matching Values

group_a = [10, 20, 30]
group_b = [15, 20, 35]

for first in group_a:
    for second in group_b:
        if first == second:
            print("Match found:", first)

Output:

Match found: 20

The code checks every possible pair until the loops finish. For small collections, this can be a simple solution. For large collections, a set or dictionary may provide a more efficient approach.

12. Number of Iterations in Nested Loops

When the inner loop executes a fixed number of times for each outer iteration, the total number of inner-body executions is the product of the iteration counts.

For example:

for i in range(3):
    for j in range(4):
        print(i, j)

The outer loop executes 3 times and the inner loop executes 4 times per outer iteration. Therefore:

Total executions = 3 × 4 = 12

Outer Iterations Inner Iterations Per Outer Iteration Total Inner-Body Executions
2 3 6
4 5 20
3 10 30
5 5 25

If the number of inner iterations changes according to the outer-loop variable, calculate the iterations for each outer pass and add them together. For example, a triangle pattern with 1, 2, 3, and 4 stars performs 1 + 2 + 3 + 4 = 10 inner-loop executions.

13. Time Complexity of Nested Loops

Time complexity describes how an algorithm's running work grows as its input becomes larger. It is often expressed using Big O notation.

13.1 Two Loops with n Iterations Each

for i in range(n):
    for j in range(n):
        process(i, j)

If each loop runs n times, the inner statement executes approximately n × n times. Its time complexity is O(n²), assuming process() takes constant time.

13.2 Different Loop Sizes

for i in range(n):
    for j in range(m):
        process(i, j)

The inner statement executes approximately n × m times. The time complexity is O(nm), assuming constant-time work inside the loop.

13.3 Triangular Iteration

for i in range(n):
    for j in range(i):
        process(i, j)

The inner loop runs 0, 1, 2, and so on up to n - 1 times. The total work grows quadratically, so the time complexity is O(n²).

Important: Nested loops do not always mean O(n²). Complexity depends on the number of iterations of each loop and the work performed inside them.

14. Common Mistakes When Applying Nested Loops

Mistake Explanation Correction
Incorrect indentation The inner loop may not be inside the outer loop as intended. Indent the inner loop and its body consistently.
Forgetting to reset a while-loop variable The inner loop may run only during the first outer iteration. Reinitialize the inner-loop counter at the appropriate point.
Unexpected break behavior break exits only the nearest enclosing loop. Use a flag or another clear control structure if both loops must stop.
Wrong range boundary The stop value of range() is excluded. Check the start, stop, and step values.
Excessive nested loops Many levels can make code slow and difficult to understand. Look for simpler algorithms, built-in functions, sets, or dictionaries.
Incorrect accumulator placement A total may carry over from one row to the next unintentionally. Initialize row-specific totals inside the outer loop.

15. Best Practices for Nested Loops

  • Choose meaningful variable names such as row, column, student, and subject.
  • Keep each loop focused on a clear task.
  • Use consistent indentation to make loop structure easy to read.
  • Test the program with small inputs before using large datasets.
  • Check whether an inner loop needs to run from the beginning for every outer iteration.
  • Use break and continue only when they make the control flow clearer.
  • Avoid modifying a collection in ways that cause items to be skipped during iteration.
  • Consider a more efficient algorithm when the number of comparisons becomes large.
  • Use built-in functions and comprehensions when they make the solution simpler and easier to maintain.

16. Practice Exercises

Exercise 1: Print a Rectangle

Write a nested loop that prints four rows with five stars in each row.

Exercise 2: Number Triangle

Print the following pattern using nested loops:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Exercise 3: Multiplication Table Grid

Print multiplication results for numbers 1 through 5, using an outer loop for the first number and an inner loop for the second number.

Exercise 4: Matrix Total

Given matrix = [[2, 4], [6, 8], [10, 12]], use nested loops to calculate the sum of all values.

Exercise 5: Search for a Pair

Given two lists, use nested loops to display values that appear in both lists.

17. Practice Exercise Solutions

Solution 1: Print a Rectangle

for row in range(4):
    for column in range(5):
        print("*", end=" ")
    print()

Solution 2: Number Triangle

for row in range(1, 6):
    for number in range(1, row + 1):
        print(number, end=" ")
    print()

Solution 3: Multiplication Table Grid

for first in range(1, 6):
    for second in range(1, 6):
        print(first * second, end="\t")
    print()

Solution 4: Matrix Total

matrix = [[2, 4], [6, 8], [10, 12]]
total = 0

for row in matrix:
    for value in row:
        total += value

print("Total:", total)

Output: Total: 42

Solution 5: Search for a Pair

first_list = [1, 2, 3, 4]
second_list = [3, 4, 5, 6]

for first in first_list:
    for second in second_list:
        if first == second:
            print("Common value:", first)

Output:

Common value: 3
Common value: 4

This solution demonstrates nested-loop comparison. If the lists are large, converting one list to a set can improve search efficiency.

18. Interview Questions and Answers

Q1. What is a nested loop in Python?

Answer: A nested loop is a loop placed inside another loop. The inner loop executes as part of the outer loop's body.

Q2. How many times does the inner loop execute?

Answer: If the outer loop executes n times and the inner loop executes m times for every outer iteration, the inner body executes n × m times.

Q3. Can Python have more than two nested loops?

Answer: Yes. Python allows multiple levels of nested loops, although too many levels can make code harder to understand and less efficient.

Q4. What happens when break is used inside an inner loop?

Answer: It terminates the nearest enclosing loop, which is usually the inner loop. The outer loop can continue.

Q5. Why must a counter be reset in a nested while loop?

Answer: If the inner loop needs to run for every outer iteration, its counter must be initialized again before the next inner-loop run.

Q6. How are nested loops used with a matrix?

Answer: The outer loop can process each row, while the inner loop processes each element within that row.

Q7. What is the time complexity of two nested loops that each run n times?

Answer: If the work inside the inner loop takes constant time, the total time complexity is O(n²).

Q8. Are nested loops always inefficient?

Answer: No. They are appropriate for tasks such as processing matrices and generating combinations. Efficiency depends on the problem size and algorithm.

Q9. What is the difference between nested loops and sequential loops?

Answer: In sequential loops, one loop finishes before another starts. In nested loops, the inner loop runs during each iteration of the outer loop.

Q10. How can nested-loop performance be improved?

Answer: Reduce unnecessary iterations, use appropriate data structures such as sets and dictionaries, move repeated calculations out of loops when possible, and consider a more efficient algorithm.

19. Quick Revision Checklist

  • A nested loop contains one loop inside another.
  • The outer loop controls the main repetition.
  • The inner loop usually completes all its iterations for each outer iteration.
  • Nested loops are useful for patterns, matrices, grids, and combinations.
  • Nested while loops need correct initialization and updates.
  • break exits the nearest enclosing loop.
  • continue skips the remainder of the current iteration.
  • Two loops with n iterations each commonly result in O(n²) work.
  • Clear indentation, meaningful names, and boundary testing reduce mistakes.
  • More efficient data structures can help avoid unnecessary nested comparisons.

20. Conclusion

Applying nested loops is an important Python skill for solving problems involving repeated operations at multiple levels. By understanding outer and inner loops, controlling iteration counts, working with matrices, generating patterns, and managing loop control statements, you can write programs that handle structured data and repeated tasks effectively.

Start with small examples, trace the values of each loop variable, and gradually practise more complex problems. Always consider readability and performance when deciding whether nested loops are the best solution.


Learn Python with JustAcademy

Explore Python training resources and continue practising programming concepts with JustAcademy.

whatsapp